<template>
  <div>
    <!-- 检索与添加 -->
    <div>
      <el-row style="margin: 10px" :gutter="2">
        <el-col span="4">
          <el-input v-model="selectForm.paperName" placeholder="请输入论文名称">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col span="1">
          <el-button type="primary" @click="this.getPaperInfo(this.pageNum)"
            >搜索</el-button
          >
        </el-col>

        <el-col span="1">
          <AddPaper></AddPaper>
        </el-col>

        <el-col span="3" :push="15">
          <el-button round @click="searchCollapseShowFun()"
            ><el-icon><search /></el-icon>高级检索</el-button
          >
        </el-col>
      </el-row>
    </div>

    <!-- 高级检索 -->
    <div>
      <!-- 折叠面板 -->
      <el-collapse class="searchHead" v-model="showSearch">
        <el-collapse-item name="search">
          <template #title
            ><el-icon size="15px"><Search /></el-icon
            >&nbsp;&nbsp;&nbsp;高级检索</template
          >

          <!-- 表单数据排版 -->
          <el-form ref="selectForm">
            <!-- 第一行 -->
            <el-row :gutter="56">
              <el-col :offset="2" :span="4"
                ><el-form-item label="论文名称"
                  ><el-input v-model="selectForm.paperName" /></el-form-item
              ></el-col>
              <el-col :span="4"
                ><el-form-item label="检索情况">
                  <el-select
                    v-model="selectForm.level"
                    placeholder="检索情况"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in level"
                      :key="item.id"
                      :label="item.levelName"
                      :value="item.id"
                    ></el-option>
                  </el-select> </el-form-item
              ></el-col>
              <el-col :span="4"
                ><el-form-item label="期刊名&nbsp;&nbsp;&nbsp;"
                  ><el-input v-model="selectForm.retrieval" /></el-form-item
              ></el-col>
              <el-col :span="4"
                ><el-form-item label="第一作者"
                  ><el-input v-model="selectForm.firstAuthor" /></el-form-item
              ></el-col>
              <el-col :span="4"
                ><el-form-item label="通信作者"
                  ><el-input
                    v-model="selectForm.correspondingAuthor" /></el-form-item
              ></el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row :gutter="56">
              <el-col :span="4" :offset="2">
                <el-form-item label="本人排名">
                  <el-input v-model="selectForm.ranking" />
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="本人所属单位">
                  <!-- <el-select :disabled="useable" v-model="selectFrom.level" placeholder="项目级别" style="width:100%">
                    <el-option v-for="item in level" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select> -->

                  <el-input v-model="selectForm.unitSelf" />
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="基金支持号">
                  <el-input v-model="selectForm.projectNum" />
                </el-form-item>
              </el-col>

              <el-col :span="4">
                <el-form-item label="基金支持项目">
                  <el-select v-model="selectForm.projectId">
                    <el-option
                      v-for="item in projectList"
                      :key="item.projectName"
                      :label="item.projectName"
                      :value="item.projectName"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行 -->
            <el-row>
              <el-col :offset="2" :span="9">
                <el-form-item label="录用时间">
                  <template style="display: flex">
                    <el-date-picker
                      placeholder="起始时间"
                      style="width: 150px"
                      v-model="selectForm.employmentDateBeg"
                    />
                    <span>&nbsp;&nbsp;&nbsp;--&nbsp;&nbsp;&nbsp;</span>
                    <el-date-picker
                      placeholder="结束时间"
                      style="width: 150px"
                      v-model="selectForm.employmentDateEnd"
                    />
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="发表时间">
                  <template style="display: flex">
                    <el-date-picker
                      placeholder="起始时间"
                      style="width: 150px"
                      v-model="selectForm.publishDateBeg"
                    />
                    <span>&nbsp;&nbsp;&nbsp;--&nbsp;&nbsp;&nbsp;</span>
                    <el-date-picker
                      placeholder="结束时间"
                      style="width: 150px"
                      v-model="selectForm.publishDateEnd"
                    />
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-button @click="this.getPaperInfo(this.pageNum)"
                >查询</el-button
              >
              <el-button
                @click="
                  this.selectForm = {};
                  this.getPaperInfo(this.pageNum);
                "
                >清空</el-button
              >
            </el-row>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      border="true"
      max-height="65vh"
      height="65vh"
      v-loading="loading"
      element-loading-text="Loading..."
      :default-sort="{ prop: 'publishDate', order: 'descending' }"
    >
      <template #empty>
        <el-empty description="未查询到数据"></el-empty>
      </template>
      <el-table-column
        type="index"
        label="序号"
        width="50px"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="paperName"
        label="论文名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="levelStr"
        label="检索情况"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="retrieval"
        label="期刊名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="firstAuthor"
        label="第一作者"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="publishDate"
        label="发表时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="employmentDate"
        label="录用时间"
        align="center"
      ></el-table-column>

        <el-table-column label="基金支持项目" align="center">
          <template #default="scope">
          <template v-if="scope.row.projectId =='其他项目'">
            {{scope.row.projectName}}
          </template>
          <template v-else>{{scope.row.projectId}}</template>
        </template>
        </el-table-column>
      <el-table-column prop="" label="操作" align="center" width="250">
        <template #default="scope">
          <el-button-group>
            <el-button
              type="primary"
              @click="detailInfo(scope.row.id)"
              :disabled="!this.hasAuth('sys:paper:detail')"
              >详情</el-button
            >
            <el-button
              type="primary"
              @click="updata(scope.row.id)"
              :disabled="
                !this.hasAuth('sys:paper:detail') ||
                !this.hasAuth('sys:paper:update')
              "
              >修改</el-button
            >
            <el-button
              type="danger"
              @click="delectInfo(scope.row.id)"
              :disabled="!this.hasAuth('sys:paper:delete')"
              >删除</el-button
            >
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      v-model:currentPage="currentPage"
      :page-size="10"
      layout="total, prev, pager, next, jumper"
      :total="total"
      @current-change="handleCurrentChange"
      background="true"
    >
    </el-pagination>

    <!-- 详情 -->
    <el-dialog v-model="dialogTableVisible" top="5vh">
      <el-scrollbar height="700px">
        <el-descriptions direction="horizontal" :column="1" border>
          <el-descriptions-item label="论文名称">{{
            detailData.paperName
          }}</el-descriptions-item>
          <el-descriptions-item label="检索情况">{{
            detailData.levelStr
          }}</el-descriptions-item>
          <el-descriptions-item label="期刊名称">{{
            detailData.retrieval
          }}</el-descriptions-item>
          <el-descriptions-item label="第一作者">{{
            detailData.firstAuthor
          }}</el-descriptions-item>
          <el-descriptions-item label="通信作者">{{
            detailData.correspondingAuthor
          }}</el-descriptions-item>
          <el-descriptions-item label="其余作者">{{
            detailData.otherAuthor
          }}</el-descriptions-item>
          <el-descriptions-item label="本人排名">{{
            detailData.ranking
          }}</el-descriptions-item>
          <el-descriptions-item label="发表时间">{{
            detailData.publishDate
          }}</el-descriptions-item>
          <el-descriptions-item label="录用日期">{{
            detailData.employmentDate
          }}</el-descriptions-item>
          <el-descriptions-item label="本人所属单位">{{
            detailData.unitSelf
          }}</el-descriptions-item>
          <el-descriptions-item label="基金支持号">{{
            detailData.projectNum
          }}</el-descriptions-item>
          <el-descriptions-item label="基金支持项目">
            <template v-if="detailData.projectId == '其他项目'">
              {{ detailData.projectName }}
            </template>
            <template v-else>
              {{ detailData.projectId }}
            </template>
          </el-descriptions-item>
          <el-descriptions-item
            label="附件"
            v-if="detailData.utilFiles.length > 0"
          >
            <template v-for="data in detailData.utilFiles" :key="data.id">
              <a
                :href="
                  'http://101.43.150.171:8082/PaperInfos/downLoad?fileName=' +
                  data.utilName +
                  '&fileNameSrc=' +
                  data.utilSrcName +
                  '&parameter=' +
                  token
                "
                >{{ data.utilSrcName }}</a
              >
              <br />
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog v-model="dialogFormToUp" title="修改" top="5vh">
      <el-scrollbar height="700px">
        <el-form
          ref="detailData"
          :model="detailData"
          label-width="120px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="论文名称" prop="paperName">
            <el-input v-model="detailData.paperName" type="text"></el-input>
          </el-form-item>
          <el-form-item label="检索情况" prop="level">
            <el-select
              v-model="detailData.level"
              placeholder="Select"
              style="width: 100%"
            >
              <el-option
                v-for="item in level"
                :key="item.id"
                :label="item.levelName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="期刊名称" prop="retrieval">
            <el-input v-model="detailData.retrieval" type="text"></el-input>
          </el-form-item>
          <el-form-item label="第一作者" prop="firstAuthor">
            <el-input v-model="detailData.firstAuthor" type="text"></el-input>
          </el-form-item>
          <el-form-item label="通信作者" prop="correspondingAuthor">
            <el-input
              v-model="detailData.correspondingAuthor"
              type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="其余作者" prop="otherAuthor">
            <el-input v-model="detailData.otherAuthor" type="text"></el-input>
          </el-form-item>
          <el-form-item label="本人排名" prop="ranking">
            <el-input
              v-model.number="detailData.ranking"
              type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="发表时间" prop="publishDate">
            <el-date-picker
              style="width: 100%"
              v-model="detailData.publishDate"
              type="date"
              placeholder="请选择发表时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="录用时间" prop="employmentDate">
            <el-date-picker
              style="width: 100%"
              v-model="detailData.employmentDate"
              type="date"
              placeholder="请选择录用时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="本人所属单位" prop="unitSelf">
            <el-autocomplete
              v-model="detailData.unitSelf"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入本人所属单位"
              @select="handleSelect"
              value-key="companyName"
              :trigger-on-focus="false"
              style="width:100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="基金支持号" prop="projectNum">
            <el-input v-model="detailData.projectNum" type="text"></el-input>
          </el-form-item>
          <el-form-item label="基金支持项目" prop="projectId">
            <el-select
              v-model="detailData.projectId"
              style="width: 100%"
              @change="this.detailData.projectName = ''"
            >
              <el-option
                v-for="item in projectList"
                :key="item.projectName"
                :label="item.projectName"
                :value="item.projectName"
              ></el-option>
              <el-option label="其他项目" value="其他项目" />
            </el-select>
          </el-form-item>

          <el-form-item
            v-show="detailData.projectId == '其他项目'"
            label="基金支持项目"
            prop="projectName"
          >
            <el-input
              v-model="detailData.projectName"
              placeholder="请输入其他基金支持项目名称"
            />
          </el-form-item>

          <el-form-item label="添加附件" prop="file">
            <el-upload
              class="upload-demo"
              :before-remove="beforeRemove"
              :on-change="fileChangeFunc"
              drag
              action=""
              multiple
              name="file"
              style="float: left"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-icon class="el-icon--upload"><Document /></el-icon>
              <div class="el-upload__text">
                拖放文件上传 或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  单个文件最大为50MB,总上传大小为100MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('detailData')"
              >修改</el-button
            >
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import AddPaper from "./addPaper.vue";
import axios from "../../utils/request";
import { ElNotification } from "element-plus";
import { Search, Document } from "@element-plus/icons";
export default {
  components: { AddPaper, Search, Document },
  inject: ["reload"], //页面刷新函数
  data() {
    return {
      dialogTableVisible: false,
      dialogFormToUp: false,
      tableData: [],
      total: "",
      detailData: {projectName:''},
      selectForm: {},
      pageNum: 1,
      currentPage: 1,
      PageSize: 10,
      loading: false,
      fileList: [],
      files: [],
      searchSenior: false,
      showSearch: "",
      // 表单校验规则
      rules: {
        paperName: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        level: [{ required: true, message: "不允许为空!", trigger: "change" }],
        retrieval: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        firstAuthor: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        correspondingAuthor: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        otherAuthor: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        ranking: [
          { required: true, message: "不允许为空!", trigger: "change" },
          {
            min: 1,
            type: "number",
            message: "请输入大于0的整数",
            trigger: "change",
          },
        ],
        publishDate: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        employmentDate: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        unitSelf: [{ required: true, message: "不允许为空!", trigger: "change" }],
        projectNum: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        projectId: [
          { required: true, message: "不允许为空!", trigger: "change" },
        ],
        projectName: [
          {
            required: true,
            validator: this.checkProjectName,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    /**
     * 表单数据校验规则
     */
    checkProjectName(rule, value, callback) {
      if(this.detailData.projectId != "其他项目"){
        callback();
      }else{
        if ( value == null || value == '') {
          callback(new Error("该字段不允许为空"));
        }else{
          callback();
        }
      }
    },

    searchCollapseShowFun() {
      this.searchSenior = !this.searchSenior;
      if (this.searchSenior) {
        this.showSearch = "search";
      } else {
        this.showSearch = "";
      }
    },
    delectInfo(id) {
      axios
        .get("/PaperInfos/delete", { params: { id: id } })
        .then((reponse) => {
          ElNotification({
            message: reponse.data.message,
            type: "success",
          });
          // this.reload();
          this.getPaperInfo(this.currentPage);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    detailInfo(id) {
      axios
        .get("/PaperInfos/detail", { params: { id: id } })
        .then((reponse) => {
          this.dialogTableVisible = true;
          this.detailData = reponse.data.data.paperInfo;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    updata(id) {
      this.fileList = [];
      axios
        .get("/PaperInfos/detail", { params: { id: id } })
        .then((reponse) => {
          this.dialogFormToUp = true;
          this.detailData = reponse.data.data.paperInfo;
          for (
            var i = 0;
            i < reponse.data.data.paperInfo.utilFiles.length;
            i++
          ) {
            this.fileList.push({
              id: reponse.data.data.paperInfo.utilFiles[i].id,
              name: reponse.data.data.paperInfo.utilFiles[i].utilSrcName,
              isExcite: true, //服务器中是否存在
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    submitForm(val) {

      this.$refs.detailData.validate((valid) => {
        if(valid){
          var formData = new window.FormData();
      formData.append(
        "paperInfo",
        new Blob([JSON.stringify(this.detailData)], {
          type: "application/json",
        })
      );
      if (this.files.length != 0) {
        this.files.forEach((data) => {
          formData.append("files", data.raw);
        });
      }
      axios.post("/PaperInfos/upData", formData).then((res) => {
        if (res.data.status === 200) {
          ElNotification({
            message: res.data.message,
            type: "success",
          });
        }
        this.dialogFormToUp = false;
        this.getPaperInfo(this.currentPage);
      });
        }else{
          return false;
        }
      })
    },
    getLevelInfo() {
      axios.get("/PaperLevel/PaperLevelAll").then((res) => {
        if (res.data.status === 200) {
          this.level = res.data.data.paperLevel;
        }
      });
    },
    getPaperInfo(pageNum) {
      this.loading = true;
      axios
        .post(
          "/PaperInfos/searchPaperInfo/" + pageNum + "/" + this.PageSize,
          this.selectForm
        )
        .then((res) => {
          this.tableData = res.data.data.pageInfo.list;
          this.total = res.data.data.pageInfo.total;
          // console.log(res)
          this.loading = false;
        });
    },
    handleCurrentChange(val) {
      this.getPaperInfo(val);
      this.currentPage = val;
    },
    hasAuth(perm) {
      var authority = this.$store.state.menus.permList;
      return authority.indexOf(perm) > -1;
    },
    // 表单文件上传函数
    beforeRemove(file, fileList) {
      console.log(fileList);
      // var re = this.$confirm(`确定将文件 ${file.name}从服务器中删除?`);
      if (file.isExcite === true) {
        axios
          .get("/UtilFiles/delete", { params: { id: file.id } })
          .then((res) => {
            ElNotification.success("文件" + res.data.message+" 删除成功！");
          });
      } else {
        this.files.splice(this.files.indexOf(file), 1);
      }
    },
    fileChangeFunc(file, fileList) {
      // console.log("file :",file);
      this.files.push(file);
      // console.log("fileList:", fileList);
    },
    //获取项目列表
    getProjectList() {
      axios.get("/ProjectInfo/projectList").then((res) => {
        this.projectList = res.data.data.projectList;
      });
    },
    /**
     * 表单校验规则回调函数
     *
     */
    projectNameIsTrue(rule, value, callback) {
      if (this.InfoForm.projectId != "-1") {
        callback();
      }
      if (value == "") {
        callback(new Error("该字段不允许为空"));
      }
      callback();
    },
    /**
     * 单位信息输入建议
     */
    //获取单位信息
    getCompanyInfo() {
      axios.get("/CompanyInfos/searchInput").then((res) => {
        // console.log(res);
        this.restaurants = res.data.data.map_companyInfo;
      });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      cb(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.companyName.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      this.detailData.unitSelfId = item.id;
    }
  },
  mounted() {
    this.getPaperInfo(this.currentPage);
    this.getLevelInfo();
    this.getProjectList();
    this.getCompanyInfo();
  },
  computed: {
    token: {
      get() {
        return localStorage.getItem("token");
      },
    },
  },
};
</script>
